<?php

namespace app\admin\controller\information;

use app\common\controller\Backend;
use think\Db;
use think\Exception;
use addons\qrcode\controller\Index;
use app\admin\library\Auth;
use app\admin\model\information\Shelves;
use app\admin\model\Kisapi;

use Mpdf\Mpdf;


/**
 * 仓库基础资料录入
 *
 * @icon fa fa-circle-o
 */
class Warehouse extends Backend
{

    /**
     * Warehouse模型对象
     * @var \app\admin\model\information\Warehouse
     */
    protected $model = null;
    protected $kcModel = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\information\Warehouse;
        $this->kcModel = new \app\admin\model\inventory\Wmskc;
        
        // if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
        //     $this->error(__('You have no permission'));
        // }
    //     $tempDir = RUNTIME_PATH . 'tmp/';
    //     if (!is_dir($tempDir)) {
    //         @mkdir($tempDir, 0755, true);
    //     }

    //     $mpdf = new Mpdf(['mode'=>'utf-8',
    //     'format' => [1,2],
    //     'tempDir' => $tempDir
    // ]);

    // $filename = '123.pdf';
    // $mpdf->SetDisplayMode('fullpage');
    // //自动分析录入内容字体
    // $mpdf->autoScriptToLang = true;
    // $mpdf->autoLangToFont = true;
    // $date=date('Ymd',time());
    // //文章pdf文件存储路径
    // $filepath=ROOT_PATH . 'public/uploads/pdf/' .$date.'/';
    // $fileUrl = $filepath. $filename;
    // if (!is_dir($filepath)) {
    //     @mkdir($filepath, 0755, true);
    // }
    // //以html为标准分析写入内容
    // if(!empty($css)){
    //     $mpdf->WriteHTML($css,1);
    // }
    // $mpdf->WriteHTML('<h1>13444</h1>');
    // //生成文件
    // $mpdf->Output($fileUrl);
    // if (is_file($fileUrl)){
    //     $domain=$this->request->domain();
    //    return $this->success('',$domain.'/uploads/pdf/' .$date.'/'. $filename);
    // } else {
    //    return $this->errorWithCode('文件生成失败！');
    // }


        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("switchList", $this->model->getSwitchList());
        $this->view->assign("sourceList", $this->model->getSourceList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 同步数据
     */
    public function getData()
    {
       $list = Kisapi::getDataByName('warehouse');
       Db::startTrans();
       try {
           $data = [];
           $id_arr = [];
           foreach ($list as $value) {
               $data[] = [
                   'id' => $value['fItemId'],
                   'name' => $value['fName'],
                   'pid' => $value['fParentId'],
                   'number' => $value['fNumber'],
                   'stocker_id' => $value['fEmpID'],
                   'switch' => db('warehouse')->where('id',$value['fItemId'])->value('switch',1),
                   'createtime'=>date('Y-m-d H:i:s',time())
               ];
               
               $id_arr[] = $value['fItemId'];
           }
           db('warehouse')->insertAll($data,true);
           
           $warehouses = $this->model::select();
           if($warehouses){
               foreach($warehouses as $warehouse){
                   if(!in_array($warehouse->id,$id_arr)){
                       if(db('wms_kc')->where([
                           'warehouse_number' => $warehouse->number,
                           'quantity' => ['GT',0]
                       ])->value('id')){
                           $this->error("仓库{$warehouse->name},存在库存,无法删除");
                       }else{
                           $warehouse->delete();
                       }
                   }
               }
           }
           
           Db::commit();
           $this->success("同步完成");
       }catch (Exception $e){
           Db::rollback();
          $this->error($e->getMessage());
       }
    }

    public function print()
    {
        $ids = $this->request->get('warehouse_id');
        $list = //Db::name('shelves')
                Shelves::where(['deletetime'=>null,'id'=>['in',$ids]])
            ->field('*,(select name from fa_warehouse as w where w.id = warehouse_id and w.deletetime is null) as houseName')
            
            ->select();
        $domain = request()->domain();
        if(empty($list)) return '暂无信息';
        
        $typeArr = $this->model->getTypeList();
        
        foreach ($list as &$v){
            //$v['qrcode']= "编码:".$v['number'].($v['type']==2? '|第'.$v['row_number'].'行 第'.$v['column_number'].'列 第'.$v['layers_number'].'层|'.$v['number']:'');
            $v['name']=($v['type']==2)?'第'.$v['row_number'].'行 第'.$v['column_number'].'列 第'.$v['layers_number'].'层':$v['name'];
            $v['type_text'] = $typeArr[$v['wh_type']];
            
        }
        unset($v);
        $this->assign('list',$list);
        return $this->view->fetch();
    }

    //选择器界面

    public function choose()
    {
       return $this->index();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            
            //判断仓库下面，有物料的则不给改属性
            if($params['type']!=$row->type){
                if($this->kcModel::checkKcByWhIDShID($ids)){
                    exception('该仓库下存在库存，无法更改属性');
                }
            }
            if($params['switch']!=$row->switch){
                if($this->kcModel::checkKcByWhIDShID($ids)){
                    exception('该仓库下存在库存，无法更改状态');
                }
            }
            ///////
            
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
}
